package cn.schoolwow.flow.monitor.module.business.scheduleJob.cases.flow;

import cn.schoolwow.flow.monitor.domain.FlowMonitorOption;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.springframework.context.ApplicationContext;

import java.time.LocalDateTime;

public class DatabaseLogCleanFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        String[] tableNames = flowContext.checkData("tableNames", String[].class);
        int remainDay = flowContext.checkData("remainDay", int.class);
        ApplicationContext applicationContext = flowContext.checkInstanceData(ApplicationContext.class);
        FlowMonitorOption flowMonitorOption = applicationContext.getBean(FlowMonitorOption.class);

        if(null==tableNames||tableNames.length==0){
            return;
        }
        LocalDateTime now = LocalDateTime.now();
        for(String tableName:tableNames){
            if(!flowMonitorOption.dao.hasTable(tableName)){
                continue;
            }
            flowMonitorOption.dao.query(tableName)
                    .addQuery("created_at", "<=", now.minusDays(remainDay))
                    .execute()
                    .delete();
        }
    }

    @Override
    public String name() {
        return "定时清理数据库日志";
    }
}
